import { onMounted, onUnmounted, onActivated, onDeactivated, ref } from 'vue'
// 防抖
import { throttle } from 'underscore'

// 方法一
// export default function useScroll(reachCallback) {
//   // 监听window创建的滚动
//   const scorllListenerHandler = () => {
//     // 自身屏幕高度
//     const clientHeight = document.documentElement.clientHeight
//     // 滚动高度
//     const scrollTop = document.documentElement.scrollTop
//     // 文档高度
//     const scrollHeight = document.documentElement.scrollHeight
//     // 自身屏幕高度+滚动高度
//     const myHeight = clientHeight + scrollTop
//     if (myHeight >= scrollHeight) {
//       // homeStore.houselistAction()
//       console.log('滚动到底部');
//       // 执行传入的函数
//       if (reachCallback) reachCallback()
//     }
//   }
//   // 进入监听
//   onMounted(() => {

//     window.addEventListener('scroll', scorllListenerHandler)
//     console.log('onMounted')
//   })
//   onActivated(() => {

//     window.addEventListener('scroll', scorllListenerHandler)
//     console.log('onActivated')
//   })
//   // 移除监听
//   onUnmounted(() => {
//     window.removeEventListener('scroll', scorllListenerHandler)
//     console.log('onUnmounted')
//   })
//   onDeactivated(() => {
//     window.removeEventListener('scroll', scorllListenerHandler)
//     console.log('onDeactivated')
//   })
// }

// 方法二:
export default function useScroll(elRef) {
  let el = window

  const isReachCallback = ref(false)

  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)
  const myScroll = ref(0)

  // 监听window创建的滚动
  // 防抖/节流
  const scorllListenerHandler = throttle(() => {
    if (el === window) {
      // 自身屏幕高度
      clientHeight.value = document.documentElement.clientHeight
      // 滚动高度
      scrollTop.value = document.documentElement.scrollTop
      // 文档高度
      scrollHeight.value = document.documentElement.scrollHeight
      myScroll.value = clientHeight.value + scrollTop.value
    } else {
      clientHeight.value = el.clientHeight
      scrollTop.value = el.scrollTop
      scrollHeight.value = el.scrollHeight
      myScroll.value = clientHeight.value + scrollTop.value
    }
    if (scrollHeight.value - myScroll.value <= 300) {
      // homeStore.houselistAction()
      console.log('滚动到底部');
      isReachCallback.value = true
    }
  }, 500)

  // 进入监听
  onMounted(() => {
    if (elRef) el = elRef.value
    el.addEventListener('scroll', scorllListenerHandler)
    // console.log('onMounted')
  })
  onActivated(() => {
    if (elRef) el = elRef.value
    el.addEventListener('scroll', scorllListenerHandler)
    // console.log('onActivated')
  })
  // 移除监听
  onUnmounted(() => {
    el.removeEventListener('scroll', scorllListenerHandler)
    // console.log('onUnmounted')
  })
  onDeactivated(() => {
    el.removeEventListener('scroll', scorllListenerHandler)
    // console.log('onDeactivated')
  })

  return {
    isReachCallback,
    clientHeight,
    scrollTop,
    scrollHeight
  }
}
